﻿using AutoMapper;
using DFGK_WMS.Context;
using DFGK_WMS.IRepository;
using DFGK_WMS.Model.DTO;
using DFGK_WMS.Model.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DFGK_WMS.Repository
{
    public class TInventoryQueryRepository : BaseRepository<TInventory>, ITInventoryQuery
    {
        public TInventoryQueryRepository(DFGK_DB context, IMapper mapper) : base(context, mapper)
        {
        }



        /// <summary>
        /// 盘点查询
        /// </summary>
        /// <param name="totalCount"></param>
        /// <param name="PalletBarcode"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public List<TInventory> GetInventoryQuery(out int totalCount, string PalletBarcode, int pageIndex, int pageSize)
        {
            var list = Context.TInventories.AsQueryable();

            if (PalletBarcode != null)
            {
                list = list.Where(x => x.PalletBarcode == PalletBarcode);
            }
            totalCount = list.Count();

            list = list.OrderByDescending(x => x.CreateDate).Skip((pageIndex - 1) * pageSize).Take(pageSize);

            return list.ToList();
        }

        /// <summary>
        /// 根据盘点计划ID查询盘点计划
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public TStocktakingPlan GetTStocktakingPlanById(long id)
        {
            if (id <= 0)
            {
                return null;
            }

            var list = Context.TStocktakingPlans.FirstOrDefault(x => x.Id == id);

            return list;
        }

        /// <summary>
        /// 根据存放库位带出库区物资数量
        /// </summary>
        /// <param name="areaId"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public List<TInventory> GetInventoryNumByAreaId(int areaId)
        {

            var list = Context.TInventories.AsQueryable();

            if (areaId > 0)
            {
                var filteredList = list.Where(x => x.AreaId == areaId).ToList();
                var sumResult = filteredList.Sum(x => x.AllocateQty);
                return filteredList;
            }

            return list.ToList();
        }

        /// <summary>
        /// 存储盘点计划列表查询
        /// </summary>
        /// <param name="inventories"></param>
        /// <param name="planId"></param>
        /// <param name="planNumber"></param>
        /// <returns></returns>
        public bool GetTInventorywuliao(List<TInventorymaterialdetailsdto> pandianDanhaodto, long planId, string planNumber)
        {

            using (var shiwu = Context.Database.BeginTransaction())
            {
                try
                {
                    TStocktakingPlan jihua = new TStocktakingPlan();//盘点计划表

                    foreach (var item in pandianDanhaodto)
                    {

                        TInventorymaterialdetailsdto shuju = new TInventorymaterialdetailsdto();
                        shuju.batch = item.batch;
                        shuju.deptName = item.deptName;
                        shuju.materialNorms = item.materialNorms;
                        shuju.materialCode = item.materialCode;
                        shuju.materialName = item.materialName;
                        shuju.planId = item.planId;
                        shuju.stockCount = item.stockCount;
                        shuju.stockId = item.stockId;
                        shuju.storeLocationCode = item.storeLocationCode;
                        shuju.storeLocationRemark = item.storeLocationRemark;
                        shuju.storeName = item.storeName;
                        shuju.storeId = item.storeId;
                        shuju.storeLocationId = item.storeLocationId;
                        var kuqu = Context.TWarehouses.Find(shuju.planId);

                        TStocktakingPlan pandianjihuaid = GetTStocktakingPlanById(shuju.Id);//根据盘点计划编号查询盘点计划列表数据
                        TStocktakingOrder pandiandingid = new TStocktakingOrder();//盘点单
                        pandiandingid.BatchNo = shuju.batch;//批次号
                        pandiandingid.MaterialName = shuju.materialName;//物资名称
                        pandiandingid.Status = 0;//创建
                        pandiandingid.TouchTimes = shuju.storeId;//仓位id
                                                                 //  pandiandingid.OrderSn = planNumber;
                      //  pandiandingid.deptName = shuju.deptName;//归属部门名称
                    //    pandiandingid.materialCode = shuju.materialCode;//物资编码
                       /// pandiandingid.materialNorms = shuju.materialNorms;//规格型号
                        pandiandingid.WarehouseCode = shuju.storeName;//仓库名称
                        pandiandingid.CellCount = Convert.ToInt32(shuju.stockCount);///库存数量
                        pandiandingid.WarehouseId = shuju.stockId;//库存明细id
                        pandiandingid.WarehouseName = shuju.storeLocationCode;//存放库位
                      //  pandiandingid.storeLocationRemark = shuju.storeLocationRemark;//存放库位描述
                        pandiandingid.WarehouseCode = shuju.storeName;//仓库名称
                        pandiandingid.CreateDate = DateTime.Now;
                        pandiandingid.PriorityLevel = shuju.planId;//关联的盘点计划的id
                       // pandiandingid.planId = planId;//盘点计划id
                        pandiandingid.CreateUserId = 1;//监盘人id
                        pandiandingid.SubmitUserId = 1;//提交人id
                        pandiandingid.AuditUserName = planNumber;//盘点单号2
                        Context.SaveChanges();
                        Context.TStocktakingOrders.Add(pandiandingid);
                        if (Context.SaveChanges() <= 0)
                        {
                            shiwu.Rollback();
                            return false;
                        }

                    }
                    TStocktakingOrderDetail stockingorder = new TStocktakingOrderDetail();//盘点明细单
                    stockingorder.OrderId = Convert.ToInt32(planId);
                    stockingorder.OrderSn = planNumber;//默认创建状态是创建
                    /*stockingorder.BatchNo = shuju.batch;//批次号
                    stockingorder.InventoryId = shuju.stockId;//库存明细id
                    stockingorder.MaterialCode = shuju.materialCode;//物资编码
                    stockingorder.MaterialName = shuju.materialName;//物资名称
                    stockingorder.OrderSn = planNumber;//盘点计划里盘点单号
                    stockingorder.CellId = shuju.storeId;//仓位
                    stockingorder.CreateDate = DateTime.Now;
                    stockingorder.SupplierName = shuju.storeName;//仓库名称
                    stockingorder.WarehouseId = 1;//提交人id*/
                    Context.TStocktakingOrderDetails.Add(stockingorder);
                    //TInventory kucun = new TInventory();//库存表 
                    //kucun.LogicalPartCode = shuju.storeId;
                    //kucun.LocationCode = shuju.storeLocationId;
                    //Context.TInventory.Add(kucun);
                    Context.SaveChanges();
                    shiwu.Commit();
                    return true;
                }
                catch (Exception)
                {
                    shiwu.Rollback();
                    return false;
                    throw new Exception("错误");
                }
            }

            //库存明细查询





        }
        /// <summary>
        /// 修改盘点单状态
        /// </summary>
        /// <param name="rid"></param>
        /// <returns></returns>
        public bool Getpandianxiugai(string Ordersn, out string message)
        {
            var robj = Context.TStocktakingOrders.FirstOrDefault(x => x.OrderSn == Ordersn);
            if (robj != null)
            {
                robj.Status = 4;
                Context.TStocktakingOrders.Update(robj);
                Context.SaveChanges();
                message = "已回传";
                return true;
            }
            message = "未回传";
            return false;
        }

        public bool UpdatePandianlist(int chuanbianhao)
        {
            using (var shiwu = Context.Database.BeginTransaction())
            {
                try
                {
                    var xiuggai = Context.TStocktakingOrders.Find(chuanbianhao);
                    TStocktakingOrder stocktakingOrder = new TStocktakingOrder();
                    stocktakingOrder.OrderSn = xiuggai.OrderSn;
                    stocktakingOrder.CreateUserId = xiuggai.CreateUserId;//监盘人id
                    TStocktakingOrderDetail liebiao = new TStocktakingOrderDetail();
                    liebiao.WarehouseId = xiuggai.WarehouseId;
                    Context.SaveChanges();
                    if (Context.SaveChanges() < 0)
                    {
                        shiwu.Rollback();
                        return false;
                    }
                    Context.TStocktakingOrders.Update(stocktakingOrder);
                    shiwu.Commit();
                    return true;
                }
                catch (Exception)
                {
                    shiwu.Rollback();
                    return false;
                    throw new Exception();
                }
            }

        }

        public bool UpdatePandianlist(TInventorymaterialdetailsdto dto)
        {
            throw new NotImplementedException();
        }
        /// <summary>
        /// pda上显示的数据
        /// </summary>
        /// <returns></returns>
        public object GetPdaxianshishuju(string? name, int pageindex, int pagesize, out int totalCount)
        {
            TInventory kucun = new TInventory();
            var alist = Context.TStocktakingOrders.AsQueryable();//盘点单
            var blist = Context.TStocktakingOrderDetails.AsQueryable();//盘点订单id
            var clist = Context.TInventories.AsQueryable();//库存表
            var dlist = Context.TWarehouses.AsQueryable();//库房
            if (!string.IsNullOrEmpty(name))
            {
                alist.Where(x => x.OrderSn == name);
            }
            var query = from a in alist
                        join b in blist
                        on a.Id equals b.OrderId
                        //join c in clist
                        // on b.CellId equals c.LocationId
                        orderby a.CreateDate descending
                        select new
                        {
                           
                            items = alist.Select(n => new {
                                batch = n.BatchNo,
                                stockCount = n.WarehouseId,
                                storeLocationCode = n.WarehouseName,
                                storeName = n.WarehouseCode,
                                // LocationCode= c.LocationCode,
                                // LocationId=c.LocationId
                            }).ToList(),
                            planId = b.OrderId,
                            planNumber = b.OrderSn
                            //items = alist.Select(n => new {
                            //    batch = n.BatchNo,
                            //    // LocationCode= c.LocationCode,
                            //    // LocationId=c.LocationId
                            //}).ToList(),
                            //planId = b.OrderId,
                            //planNumber = b.OrderSn
                        };
            totalCount = query.Count();
            return query;
        }




    }
       
        
        }
